class RunsController < ApplicationController
  include Authorizer
  include Configurator
  layout 'standart'
  # TODO: виж дали това наистина е задължително за всички action-и.
  before_filter :login_required, :except => [:show, :index]

  def new
    config = load_config
    @languages = config['language'].values()
    @user = session[:user]
    @problems = Problem.find(:all)
    @default_problem = session[:problem_wanted]
    session[:problem_wanted] = nil
    @run = Run.new
    @problem_id = params[:problem_id]
  end

  def create
    if (params[:run][:source_code].nil? or params[:run][:source_code].length == 0) && params[:uploaded_source].class != ActionController::UploadedStringIO
      @default_user = params[:id]
      @default_problem = params[:problem_id]
      @default_about = params[:about]
      flash[:error] = "No source code provided!"
      render :action => :new
    else
      if (params[:run][:source_code].nil? or params[:run][:source_code].length == 0)
        params[:run][:source_code] = params[:uploaded_source].read
      end 
      params[:run][:problem_id] = params[:problem_id]
      @run = Run.new(params[:run])
      @run.submit_time = Time.now.to_s
      @run.user_id = @current_user.id
      @run.status = "waiting..."
      @run.log = "no log"
      #TODO: huh?
      @run.source_name = "What source?!"
      if @run.save 
        flash[:notice] = "Submission Successful!"
        # TODO: Оправи това да сочи към по-смислено място
        redirect_to :root
      else
        @default_user = params[:user_id]
        @default_about = params[:about]
        @default_problem = params[:problem_id]
        redirect_to :controller => :runs, :action => :new
      end
    end
  end

  def show
    run = Run.find_by_run_id(params[:id])
    if run
      @run = run
      @language = run.language
      # Това оправя странния бъг, в който първият ред се показва по различен начин
      # TODO: разбери на какво се дължи този бъг.
      @run.source_code = "    " + @run.source_code
      run_user = run.user
      end_time = run.problem.contest.start_time + run.problem.contest.duration*60
      @authorized = run_user == @current_user || end_time < Time.now
    end   
  end

  def index
    # TODO: contest_id
    conditions = {}
    [:user_id, :problem_id, :language, :status].each do |criteria|
        if params[criteria] and params[criteria] != ""
            conditions[criteria] = params[criteria]
        end
    end
    # Hack. вбъдеще, помисли как да го оправиш
    params[:order] = params[:order] || "run_id"
    @runs = Run.paginate :page => params[:page], :conditions => conditions, :order => "#{params[:order]} DESC"
  end

end
